<template>
  <div ref="line" class="line-container"></div>
</template>

<script>
export default {
  name: 'bar-chart',
  data() {
    return {
      xAxisData: [],
      series: []
    }
  },
  props: ['data', 'legendColor', 'legendArr', 'title'],
  watch: {
    data: {
      handler() {
        this.setChart()
      }
    }
  },
  methods: {
    setChart() {
      if (this.data) {
        this.xAxisData = []
        this.series = []
        this.data.forEach(item => {
          this.xAxisData.push(item.key)
        })
        this.series.push({
          data: this.data.map(item => item.value),
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        })
        this.initChart()
      }
    },
    initChart() {
      const options = {
        title: {
          text: this.title
        },
        color: this.legendColor || ['#379ad6'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: this.legendArr || [],
          icon: 'roundRect',
          y: 'bottom',
          x: 'left',
          padding: [10, 0, 0, 40],
          itemWidth: 20,
          itemHeight: 1,
          itemGap: 33
        },
        xAxis: [{
          type: 'category',
          data: this.xAxisData
        }],
        yAxis: [{
          type: 'value'
        }],
        series: this.series
      }
      this.$echarts.dispose(this.$refs.line)
      const chart = this.$echarts.init(this.$refs.line)
      window.onresize = chart.resize
      chart.setOption(options)
    }
  }
}
</script>

<style>
</style>
